package controller;

import model.Board;
import model.GameColor;
import model.Move;
import model.Player;

public class Game {
	private Board board;
	private Move move;
	private Player playerBlack;
	private Player playerWhite;
	
	public Game(){
		board = new Board();
		move = Move.Set;
		playerBlack = new Player(GameColor.Black);
		playerWhite = new Player(GameColor.White);
	}
	
	public Game(Board board, Player player1, Player player2, Move move) {
		this.board = board;
		this.move = move;
		this.playerBlack = player1;
		this.playerWhite = player2;
	}

	public void reset() {
		this.board.reset();
		this.playerBlack.reset();
		this.playerWhite.reset();
		this.playerBlack.toggleActive();
	}

	public Object getBoard() {		
		return this.board;
	}

	public String toString(){
		return board.toString()+"\n"+playerBlack.toString()+"   "+playerWhite.toString();		
	}
	
	public Player getCurrentPlayer() {		
		return playerBlack.getIsActive()? playerBlack: playerWhite;
	}

	public void toggleActivePlayer() {
		playerBlack.toggleActive();
		playerWhite.toggleActive();
		
		if(this.getCurrentPlayer().getFreeStones() > 0){
			this.move = Move.Set;
		}else{
			if(this.getCurrentPlayer().getStonesOnBoard() >= 3){
				this.move = Move.Jump;
			}else{
				this.move = Move.Move;
			}
		}
	}

	public boolean isFinished() {
		if(playerBlack.getFreeStones() == 0 && playerBlack.getStonesOnBoard() < 3 ||
				playerWhite.getFreeStones() == 0 && playerWhite.getStonesOnBoard() < 3){
			return true;
		}
		if(!board.playerHasMoveLeft(playerBlack) || !board.playerHasMoveLeft(playerWhite)){
			return true;
		}
		return false;
	}

	public void setStone(int z, int y, int x) throws IllegalPositionException {
		if(!board.checkPosition(z, y, x)){
			//TODO Error
			throw new IllegalPositionException(z, y, x);
		}
		board.setStone(z, y, x, getCurrentPlayer().getColor());
		if(board.isStoneInMill(z, y, x)){
			this.move = Move.Remove;
		}else{
			toggleActivePlayer();			
		}
	}
	
	public void removeStone(int z, int y, int x) throws IllegalPositionException {
		if(!board.checkPosition(z, y, x)){
			//TODO ERROR
			throw new IllegalPositionException(z, y, x);
		}
		if(move == Move.Jump || move == Move.Move){
			board.removeStone(z, y, x, getCurrentPlayer().getColor());
		}else{
			if(getCurrentPlayer().getColor() == GameColor.Black){
				board.removeStone(z, y, x, GameColor.White);			
			}else{
				board.removeStone(z, y, x, GameColor.Black);				
			}
			toggleActivePlayer();
		}
	}
		
	public Move getMove(){
		return move;
	}
	
	public void setMove(Move m){
		this.move = m;
	}
}
